//
//  ProductListController.m
//  jang
//
//  Created by lee han on 08/04/2017.
//  Copyright © 2017 lee han. All rights reserved.
//

#import "ProductListController.h"
#import "ProductCell.h"
#import "CommonView.h"
#import "UIImageView+WebCache.h"
#import "ProductInfoController.h"
#import "CRUserData.h"

@interface ProductListController ()

@end

@implementation ProductListController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = _mTitle;
    
    [self.navigationItem.backBarButtonItem setTitle:@""];
    
    [_mTableView registerNib:[UINib nibWithNibName:@"ProductCell" bundle:nil] forCellReuseIdentifier:@"ProductCell"];
    _mTableView.delegate = self;
    _mTableView.dataSource = self;
    
    mRowCount = 1;
    if(_mMaxPage > 0){
        NSInteger count = [_mListData count];
        mRowCount = count / 2 + (count % 2 > 0 ? 1 : 0) + 1;
    }
    
    mCurrentPage = 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    if(self.tabBarController.tabBar.hidden == YES)
        self.tabBarController.tabBar.hidden = NO;
    [super viewWillAppear:animated];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)refreshView{
    NSInteger count = [_mListData count];
    mRowCount = count / 2 + (count % 2 > 0 ? 1 : 0) + 1;
    [_mTableView reloadData];
}

-(void)onClickMore:(id)sender{
    if(mCurrentPage >= _mMaxPage)
        return;
    if(_mCategoryID == -1){
        //爆款
        NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", (long)(mCurrentPage)], @"page", nil];
        
        [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_BurstSectionList];
    }
    else if (_mCategoryID == -2){
        //搜索
        NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:_mSearchString, @"search", [NSString stringWithFormat:@"%ld", (long)(mCurrentPage)], @"page", nil];
        
        [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_search];
    }
    else{
        NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", (long)_mCategoryID], @"categoryid",[NSString stringWithFormat:@"%ld", (long)(mCurrentPage)], @"page", nil];
        
        [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_ProductList];
    }
}

#pragma mark UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row < mRowCount - 1)
        return 186;
    return 30;
}
//end UITableViewDelegate

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return mRowCount;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == mRowCount - 1){
        UITableViewCell* lastcell = [[UITableViewCell alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        lastcell.backgroundColor = [UIColor clearColor];
        
        UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        
        button.backgroundColor = [UIColor clearColor];
        
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
   
        if(mCurrentPage < _mMaxPage){
            [button setTitle:@"点击加载更多" forState:UIControlStateNormal];
        }
        else if(mCurrentPage == _mMaxPage){
            [button setTitle:@"" forState:UIControlStateNormal];
        }
        else{
            [button setTitle:@"没有商品" forState:UIControlStateNormal];
        }
        
        [button addTarget:self action:@selector(onClickMore:) forControlEvents:UIControlEventTouchUpInside];
        
        [lastcell addSubview:button];
        
        return lastcell;
        
    }
    ProductCell *cell = [_mTableView dequeueReusableCellWithIdentifier:@"ProductCell" forIndexPath:indexPath];
    
    cell.mButton2.hidden = YES;
    
    NSInteger index = indexPath.row * 2;
    cell.mButton1.mName.text = [[_mListData objectAtIndex:index] objectForKey:@"pname"];
    cell.mButton1.mPrice.text = [[_mListData objectAtIndex:index] objectForKey:@"price"];
    
    NSString* urlstr = [URLIMAGE_PRE stringByAppendingString:[[_mListData objectAtIndex:index] objectForKey:@"path"]];
    [cell.mButton1.mImage sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"wenhao.png"]];
    
    NSString* pid = [[_mListData objectAtIndex:index] objectForKey:@"id"];
    
    if([[CRUserData sharedInstance] hasCollection:pid]){
        [cell.mButton1.mButton setTitle:@"取消" forState:UIControlStateNormal];
    }
    else{
        [cell.mButton1.mButton setTitle:@"收藏" forState:UIControlStateNormal];
    }
    
    cell.mButton1.mProductID = [pid integerValue];
    cell.mButton1.mDelegate = self;
    
    ++index;
    if(index >= [_mListData count])
        goto end;
    cell.mButton2.hidden = NO;
    cell.mButton2.mName.text = [[_mListData objectAtIndex:index] objectForKey:@"pname"];
    cell.mButton2.mPrice.text = [[_mListData objectAtIndex:index] objectForKey:@"price"];
    
    urlstr = [URLIMAGE_PRE stringByAppendingString:[[_mListData objectAtIndex:index] objectForKey:@"path"]];
    [cell.mButton2.mImage sd_setImageWithURL:[NSURL URLWithString:urlstr] placeholderImage:[UIImage imageNamed:@"wenhao.png"]];
    
    pid = [[_mListData objectAtIndex:index] objectForKey:@"id"];
    if([[CRUserData sharedInstance] hasCollection:pid]){
        [cell.mButton2.mButton setTitle:@"取消" forState:UIControlStateNormal];
    }
    else{
        [cell.mButton2.mButton setTitle:@"收藏" forState:UIControlStateNormal];
    }
    cell.mButton2.mProductID = [pid integerValue];
    cell.mButton2.mDelegate = self;
    
end:
    return cell;
}

//end UITableViewDataSource


#pragma mark networkDelegate

- (void)parserResult:(NSDictionary *)response functionType:(NSInteger)type
{
    if (type == NetworkFunctionType_ProductList || type == NetworkFunctionType_BurstSectionList){
        if([[response objectForKey:@"status"] integerValue] == 1){
            mCurrentPage = [[response objectForKey:@"curpage"] integerValue];
            _mMaxPage = [[response objectForKey:@"page"] integerValue];
            
            if(_mListData == nil){
                _mListData = [response objectForKey:@"data"];
            }
            else{
                _mListData = [_mListData arrayByAddingObjectsFromArray:[response objectForKey:@"data"]];
            }
            
            [self refreshView];
        }
        else{
            [CommonView addAlertView:self Text:@"产品列表错误"];
        }
    }
    else if (type == NetworkFunctionType_ProductInfo){
        if([[response objectForKey:@"status"] integerValue] == 1){
            //goto productinfo view
            mProductBaseInfo = nil;
            mProductReseverInfo = nil;
            for (NSDictionary* info in _mListData) {
                if([info objectForKey:@"id"]== [response objectForKey:@"id"]){
                    mProductBaseInfo = info;
                    mProductReseverInfo = [response objectForKey:@"data"];
                    break;
                }
            }
            
            if(mProductBaseInfo != nil && mProductReseverInfo != nil){
                self.tabBarController.tabBar.hidden = YES;
                [self performSegueWithIdentifier:@"plisttopinfo" sender:self];
            }
        }
        else{
            [CommonView addAlertView:self Text:@"获取产品错误"];
        }
    }
}
//end networkDelegate

#pragma mark ProductCellButtonDelegate
- (void)onClickProductCellButton:(NSInteger)pid{
    NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld", (long)pid], @"pid", nil];
    
    [[network sharedInstance] startHttpRequest:self Data:data functionType:NetworkFunctionType_ProductInfo];
}
//end ProductCellButtonDelegate

- (void)prepareForSegue: (UIStoryboardSegue *)segue sender:(id)sender{
    ProductInfoController *destination = segue.destinationViewController;
    
    destination.mBaseInfo = mProductBaseInfo;
    destination.mReseverInfo = mProductReseverInfo;
}

@end
